<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/1/26
 * Time: 11:46.
 */

declare(strict_types=1);

namespace App\Application\Api\Controller;

use App\Annotation\Api;
use App\Application\Admin\Model\Order;
use App\Application\Admin\Model\Package;
use App\Application\Admin\Model\Room;

use App\Application\Admin\Model\Roomlabel;
use App\Application\Admin\Model\Store;
use App\Application\Admin\Model\Vip;
use App\Application\Admin\Service\AdminSettingService;
use App\Application\Admin\Service\CityService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Controller;

#[Controller("/api/room")]
class RoomController extends AbstractController
{
    #[Inject]
    protected AdminSettingService $setting;

    #[Api]
    #[PostMapping("info")]
    function info()
    {
        $store_id = $this->request->input('store_id', '');
        $city_list = CityService::getInstance()
            ->getAllcity();
        $store = Room::where('store_id', $store_id)->select('*')
            ->first() ?: [];
        return compact('city_list', 'store');
    }

    /*
     *
     *门店包厢列表
     * */
    #[Api]
    #[GetMapping("lists")]
    function lists()
    {
        $store_id = $this->request->input('store_id', '');
        $where = [];
        $where[] = ['store_id', '=', $store_id];
        $lists = Room::where($where)
            ->select('*')
            ->get()->toArray();

        $notice = Store::where('store_id', $store_id)->value('notice');
        foreach ($lists as $k => $v) {

            //标签
            $lists[$k]['labelval'] = Roomlabel::whereIn('room_label_id', $v['label'])
                ->pluck('name');
            //套餐
            $lists[$k]['packageval'] = Package::whereIn('package_id', $v['package_id'])
                ->where('type', 0)
                ->orderBy('price', 'asc')->select('*')->get()->toArray();
            //状态
            //进行中订单
            $order_1 = Order::where('room_id', $v['room_id'])
                ->where('add_time', '>', time())
                ->where('end_time', '>', time())
                ->select(['status', 'end_time'])
                ->get()->toArray();
            //未开始订单
            $order_0 = Order::where('room_id', $v['room_id'])
                ->where('status', '=', 0)
                ->orderBy('end_time', 'asc')
                ->select(['status'])
                ->get()->toArray();
            //保洁
            $order_2 = Order::where('room_id', $v['room_id'])
                ->whereIn('status', ['2', '3', '4', '5'])
                ->orderBy('end_time', 'desc')
                ->select(['status'])
                ->get()->toArray();
            if (!empty($order_1)) {
                $lists[$k]['order_status'] = 3;
                $lists[$k]['end_time'] = date('H:i', $order_1[0]['end_time']);
            } else if (!empty($order_0)) {
                $lists[$k]['order_status'] = 1;
                $lists[$k]['end_time'] = date('H:i', $order_0[0]['end_time']);
            } else if (!empty($order_5)) {
                $lists[$k]['order_status'] = $order_0[0]['cleaner_status'] == 0 ? 5 : 2;
                if ($order_0[0]['cleaner_status'] == 0) {
                    $lists[$k]['order_status'] = 5;
                }
                if ($order_0[0]['cleaner_status'] == 1) {
                    $lists[$k]['order_status'] = 2;
                }
                $lists[$k]['end_time'] = date('H:i', $order_0[0]['end_time'] + 1800);
            } else {
                $lists[$k]['order_status'] = 0;
            }
            //是否在保洁
        }
        usort($lists, function ($a, $b) {
            // 如果两个元素的priority都等于1，则保持它们的相对顺序（返回0）
            if ($a['order_status'] == 0 && $b['order_status'] == 0) {
                return 0;
            }
            // 如果第一个元素的priority等于1，则它应该排在前面
            if ($a['order_status'] == 0) {
                return -1;
            }
            // 如果第二个元素的priority等于1，则它应该排在后面
            if ($b['order_status'] == 0) {
                return 1;
            }
            // 如果两个元素的priority都不等于1，则按照正常的数值比较来排序
            return $a['order_status'] - $b['order_status'];
        });
        $user = $this->checkToken();
        //余额记录  0  入账  1出账
        $balance0 = Db::table('balance_log')->where('member_id', $user['member_id'])->where('store_id', $store_id)->where('type', 0)->sum('balance');
        $balance1 = Db::table('balance_log')->where('member_id', $user['member_id'])->where('store_id', $store_id)->where('type', 1)->sum('balance');
        $balance = number_format($balance0 - $balance1, 2);
        return compact('lists', 'balance', 'notice');

    }


    /*
 *
 *门店包厢预约详情
 * */
    #[Api]
    #[PostMapping("PackageCourseTime")]
    function PackageCourseTime()
    {
        $room_id = $this->request->input('room_id', '');
        $where = [];
        $where[] = ['room_id', '=', $room_id];
        $packageids = Room::where($where)
            ->value('package_id');

        $package = Package::whereIn('package_id', $packageids)
            ->where('type', 0)
            ->select('*')
            ->orderBy('price', 'asc')
            ->get()->toArray();
        $admintime = Store::where('store_id', $package[0]['store_id'])->value('time');
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        $orders = Order:: where('room_id', $room_id)->where('add_time', '>', time() - 10 * 3600)->whereIn('status', [0, 1, 2, 5])
            ->select('*')
            ->orderBy('end_time', 'desc')
            ->get()->toArray();
        $da = [];
        $da['add_time'] = 0;
        $da['end_time'] = 0;

        foreach ($orders as $k => $v) {
            $add_hour = $v['add_time'];
            $end_hour = $v['end_time'] + $admintime * 60;

            if (self::is_time_cross($add_hour, $end_hour, time(), time() + $package[0]['time'] * 60)) {
                $da['end_time'] = $end_hour;

            }

        }

        if ($da['end_time']) {
            $end_time = date('Y-m-d H:i:s', $da['end_time']);
        } else {
            $end_time = 0;
        }

        return compact('package', 'end_time', 'orders');

    }


    /*
 *
 *门店包厢列表
 * */
    #[Api]
    #[GetMapping("storelists")]
    function storelists()
    {
        $store_id = $this->request->input('store_id', '');
        $where = [];
        $where[] = ['store_id', '=', $store_id];
        $lists = Room::where($where)
            ->select('*')
            ->get()->toArray();
        foreach ($lists as $k => $v) {
            //状态
            //进行中订单
            $order_1 = Order::where('room_id', $v['room_id'])
                ->where('add_time', '>', time())
                ->where('end_time', '>', time())
                ->select(['status', 'end_time'])
                ->get()->toArray();
            //未开始订单
            $order_0 = Order::where('room_id', $v['room_id'])
                ->where('status', '=', 0)
                ->orderBy('end_time', 'asc')
                ->select(['status'])
                ->get()->toArray();
            //保洁
            $order_2 = Order::where('room_id', $v['room_id'])
                ->whereIn('status', ['2', '3', '4', '5'])
                ->orderBy('end_time', 'desc')
                ->select(['status'])
                ->get()->toArray();
            if (!empty($order_1)) {
                $lists[$k]['order_status'] = 3;

            } else if (!empty($order_0)) {
                $lists[$k]['order_status'] = 1;

            } else if (!empty($order_5)) {
                $lists[$k]['order_status'] = $order_0[0]['cleaner_status'] == 0 ? 5 : 2;
                if ($order_0[0]['cleaner_status'] == 0) {
                    $lists[$k]['order_status'] = 5;
                }
                if ($order_0[0]['cleaner_status'] == 1) {
                    $lists[$k]['order_status'] = 2;
                }

            } else {
                $lists[$k]['order_status'] = 0;
            }


            //是否在保洁
            //今日营业统计
            $orderday = Order::where($where)
                ->whereIn('status', [0, 1, 5])
                ->where('pay_time', '>', strtotime(date('Y-m-d')))
                ->sum('pay_price');
            $orderdaysum = Order::where($where)
                ->whereIn('status', [0, 1, 5])
                ->where('pay_time', '>', strtotime(date('Y-m-d')))
                ->count('*');
            $vipday = Db::table('vip_order')->where($where)
                ->whereIn('status', [1, 2])
                ->where('pay_time', '>', strtotime(date('Y-m-d')))
                ->sum('price');
            $couponday = Db::table('coupon_order')->where($where)
                ->whereIn('status', [1, 2])
                ->where('pay_time', '>', strtotime(date('Y-m-d')))
                ->sum('price');
            //最近12小时订单
            $orderlist = Order::where($where)
                ->where('created_at', '>', date('Y-m-d hH:i:s', strtotime('-1day')))
                ->orderBy('created_at', 'desc')
                ->select('*')
                ->get()->toArray();

        }
        return compact('lists', 'orderday', 'vipday', 'couponday', 'orderdaysum', 'orderlist');

    }


    /*
     *
     *门店管理门禁指令
     *
     * */
    #[Api]
    #[PostMapping("doorcommand")]
    function doorcommand()
    {
        $door_id = $this->request->input('doorId', '');
        $door_type = $this->request->input('doorType', '');
        $status = $this->request->input('status', '');
        $room = Room::where('door_id', $door_id)->select('*')
            ->first() ?: [];
        //当前时间是否有订单进行
        $order = Order::where('room_id', '=', $room->room_id)->where('status', 'in', [1])->select('*')->first() ?: [];
        $door_type = $room->door_type;
        //计算结束时间   倒计时门禁版本
        if (empty($order)) {
            $end_time = self::end_time($room->room_id, $order->user_id, $order->end_time);
        } else {
            $store = Store::where('store_id', $room->store_id)->select('*')
                ->first() ?: [];
            $end_time = time() + $store->time * 60;

        }

        switch ($door_type) {
            case '0':
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('res');
                } else {
                    return false;
                }

                break;
            case '1':
                //版本2
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('res');
                } else {
                    return false;
                }
                break;
            case '2':
                //版本3
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('res');
                } else {
                    return false;
                }
                break;

            default:
                //版本1
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('res');
                } else {
                    return false;
                }
                break;
        }


    }

    /*
     *
     *订单门禁指令
     *
     * */
    #[Api]
    #[PostMapping("open")]
    function open()
    {
        $order_on = $this->request->input('order_on', '');
        $room_id = $this->request->input('room_id', '');
        $order = Order::where('order_on', '=', $order_on)->select('*')->first() ?: [];
        $room = Room::where('room_id', $room_id)->select('*')
            ->first() ?: [];
        $door_type = $room->door_type;
        //计算结束时间   倒计时门禁版本
        $user = $this->checkToken();
        $end_time = self::end_time($room_id, $user->member_id, $order->end_time);

        switch ($door_type) {
            case '0':
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('end_time');
                } else {
                    return false;
                }

                break;
            case '1':
                //版本2
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('end_time');
                } else {
                    return false;
                }
                break;
            case '2':
                //版本3
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('end_time');
                } else {
                    return false;
                }
                break;

            default:
                //版本1
                //版本1
                $api = 'https://zly.qile168.net/api/index/postapi';
                $access_token = 1;
                $param = ['a' => 1, 'b' => 2];
                $header = [
                    'Content-Type: application/json',
                    'Access-Token:' . $access_token
                ];
                $res = self::postApiJson($api, $param, $header);
                if ($res['code'] == 200) {
                    return compact('end_time');
                } else {
                    return false;
                }
                break;
        }


    }

}